using System.ComponentModel;
using System.Windows.Forms;
using BizTalk.BuildGenerator.MetaData;
using BizTalk.BuildGenerator.UI.Navigation;
using System;

namespace BizTalk.BuildGenerator.UI.UserControls
{
    public partial class GenerateFilesControl : UserControl, IWizardControl
    {
        public delegate void GenerationCompleteDelegate();

        public event GenerationCompleteDelegate GenerationComplete;


        private GenerationArgs _args;


        public GenerateFilesControl()
        {
            InitializeComponent();
        }

        public void RegisterArgs(GenerationArgs args)
        {
            _args = args;
        }

        #region IWizardControl Members

        public MoveNextResult MoveNext()
        {
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += BackgroundWorkerDoWork;
            backgroundWorker.ProgressChanged += BackgroundWorkerProgressChanged;
            backgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted;
            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.RunWorkerAsync(_args);
            var result = new MoveNextResult {CanMoveNext = false};
            return result;
        }

        #endregion

        private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var providerType = Type.GetType(_args.GenerationProvider, false, true);
            if (providerType == null)
                throw new ApplicationException("Invalid Generation Provider");

            var buildProvider = (IBuildProvider)Activator.CreateInstance(providerType);
            buildProvider.Update += UpdateProgress;
            buildProvider.CreateBuild(_args);            
        }

        private void UpdateProgress(int percentageComplete)
        {
            try
            {
                backgroundWorker.ReportProgress(percentageComplete);
            }
// ReSharper disable EmptyGeneralCatchClause
            catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
            { }
        }


        private void BackgroundWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            StatusProgressBar.Value = e.ProgressPercentage;
        }

        private void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.ToString());
            }
            if (GenerationComplete != null)
                GenerationComplete();
        }
    }
}